package org.example.service;

import lombok.extern.slf4j.Slf4j;
import org.example.entity.User;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 缓存管理器
 */
@Service
@CacheConfig(cacheNames = "user") //注解用于抽取缓存的公共配置
@Slf4j
public class CacheService {
    /**
     * cacheNames / value 缓存的名字
     * key 指定缓存数据使用的key，默认是方法参数的值
     * keyGenerator 自定义key生成器
     */
    @Cacheable(value = "user", key = "#id")
    public List<User> getUsers (Integer id) {
        List<User> users = new ArrayList<>();
        users.add(new User(1, "hello", "111@qq.com"));
        users.add(new User(2, "hello world", "world@qq.com"));
        users.add(new User(3, "hello cache", "cache@qq.com"));
        log.info("init cache {}", id);
        return users;
    }

    /**
     * allEntries 删除掉整个缓存
     * beforeInvocation 缓存清除是否在方法执行前执行。如果不是，方法异常则不会清除
     */
    @CacheEvict(value = "user", key = "#id" )
    public void remove(Integer id) {
        log.info("remove cache {}", id);
    }

    @CachePut(value = "user", key = "#id")
    public List<User> update(Integer id) {
        List<User> users = new ArrayList<>();
        users.add(new User(4, "update", "111@qq.com"));
        users.add(new User(5, "hello update", "world@qq.com"));
        users.add(new User(6, "update cache", "cache@qq.com"));
        log.info("update cache {}", id);
        return users;
    }


    /**
     * Caching 缓存规则复杂时使用的注解
     */
    @Caching(
            cacheable = @Cacheable(value = "user", key = "#id"),
            put = @CachePut(value = "user", key = "#id"),
            evict = @CacheEvict(value = "user", key = "#id")
    )
    public List<User> cache(Integer id) {
        List<User> users = new ArrayList<>();
        users.add(new User(4, "update", "111@qq.com"));
        users.add(new User(5, "hello update", "world@qq.com"));
        users.add(new User(6, "update cache", "cache@qq.com"));
        log.info("update cache {}", id);
        return users;
    }
    
}



